package com.github.tangmonkmeat;

/**
 * Description:
 *
 * @author zwl
 * @version 1.0
 * @date 2021/7/19 下午2:25
 */
public class 压缩字符串 {

    public static void main(String[] args) {

        String res = compressString("abc");
        System.out.println(res);

    }

    public static String compressString (String str) {
        int len = str.length();
        if (len <= 1){
            return str;
        }
        char[] cs = str.toCharArray();
        StringBuilder res = new StringBuilder();
        int n = 1;
        for (int i = 1; i < len; i++) {
            if (cs[i] != cs[i - 1]){
                res.append(cs[i - 1]).append(n);
                if (res.length() >= len){
                    return str;
                }
                n = 1;
            }else {
                n++;
            }
        }
        res.append(cs[len - 1]).append(n);
        return res.length() < len ? res.toString() : str;
    }
}
